<?php
/**
 * Geneone: Content Management Framework
 * User: Account Registration
 *
 * http://geneone.neondragon.net/
 *
 * @package Geneone
 * @author Khlo
 * @version 1.0
 * @copyright 2004-2006 Geneone Development Team
 */
 
class Gene_Special_Register {
	/**
	 * Default Action
	 */
	function main() {
		$tpl =& Gene::getTemplate();
		$auth =& Gene::getAuth();
		$db =& Gene::getDatabase();
		$tpl->assign ("pagetitle", "Create an Account");
		
		/* Already logged in users */
		if ($auth->loggedIn()) {
			header ("Location: ".Gene::makeLink(Gene::getSetting("default_obj")));
			exit();
		}
		
		/* Add additional stylesheets */
		$tpl->append("stylesheets", "register");
		$tpl->append("scripts", "register");
		
		$tpl->assign ("captcha", Gene::getSetting("reg_captcha"));
		
		$confirmkey = Gene_Request::getString("confirmcode", GENE_REQUEST_GET | GENE_REQUEST_POST);
		$confirmemail = Gene_Request::getEmail("confirmemail", GENE_REQUEST_GET | GENE_REQUEST_POST);
		
		if (Gene::getSetting("require_email_confirm") AND (!$confirmkey OR !$confirmemail)) {
			$tpl->assign ("finalbody", $tpl->fetch("special/confirmemail"));
		} else {
			if (Gene::getSetting("require_email_confirm")) {
				$q = $db->prepare ("SELECT * FROM ".Gene::tableName("email_confirm")." WHERE confirm_key=? AND email=?");
				$res = $q->execute(array($confirmkey, $confirmemail));
				if ($row = $res->fetchRow()) {
					$res->free();
					$tpl->assign ("confirmed", $row);
				} else {
					$tpl->assign ("errormsg", "We could not confirm your e-mail address. The confirmation may have expired or you may have mis-typed the confirmation code or e-mail address.");
					$tpl->assign ("finalbody", $tpl->fetch("special/confirmemail"));
					return;
				}
				$tpl->assign ("require_confirm", true);

				$email = $confirmemail;
			} else {
				$email = Gene_Request::getEmail("regemail", GENE_REQUEST_POST);
			}
			$password = Gene_Request::getString("regpassword", GENE_REQUEST_POST);
			$password2 = Gene_Request::getString("regpassword2", GENE_REQUEST_POST);
			$name = Gene_Request::getString("regname", GENE_REQUEST_POST);
			$captchacode = Gene_Request::getString("regcode", GENE_REQUEST_POST);
			$terms = Gene_Request::getString("terms", GENE_REQUEST_POST);
	
			if ($_SERVER['REQUEST_METHOD'] == 'POST') {
				if ($password != $password2) {
					$tpl->assign("email", $email);
					$tpl->assign("name", $name);
					
					$tpl->assign("errormsg", "The passwords you entered did not match.");
					$tpl->assign("finalbody", $tpl->fetch("special/register"));
				} else if ($terms != "I have read and agree to the Terms of Service.") {
					$tpl->assign("email", $email);
					$tpl->assign("password", $password);
					$tpl->assign("password2", $password2);
					$tpl->assign("name", $name);

					$tpl->assign("errormsg", "You must read and agree to the terms of service before continuing.");
					$tpl->assign("finalbody", $tpl->fetch("special/register"));
				} else if (Gene::getSetting("reg_captcha") && $captchacode != $_SESSION['captcha_regphrase']) {
					$tpl->assign("email", $email);
					$tpl->assign("password", $password);
					$tpl->assign("password2", $password2);
					$tpl->assign("name", $name);
					
					$tpl->assign("errormsg", "You must enter the code correctly to prove that you are human.");
					$tpl->assign("finalbody", $tpl->fetch("special/register"));
				} else {
					// Create the account
					$user = Gene_User::newUser($email, $password, $name, Gene::getSetting("default_ugroups"));
					if (PEAR::isError($user)) {
						$tpl->assign("email", $email);
						$tpl->assign("password", $password);
						$tpl->assign("password2", $password2);
						$tpl->assign("name", $name);
					
						$tpl->assign("errormsg", $user->getMessage());
						$tpl->assign("finalbody", $tpl->fetch("special/register"));
						return;
					} else {
						// Logout if currently logged in
						if ($auth->getAuth()) {
							$auth->logout();
							session_unset();
						}

						// Login
						$auth->doLogin($email, $password);
					
						// Garbage collection
						if (Gene::getSetting("require_email_confirm")) {
							$q = $db->prepare ("DELETE FROM ".Gene::tableName("email_confirm")." WHERE timestamp < ? OR email=?");
							$q->execute(array(time()-604800, $email));
						}
		
						// Redirect to Community New User Page
						header ("Location: ".Gene::makeLink(Gene::metaId("New_Users")));
						exit();
					}
				}
			} else {
				$tpl->assign("finalbody", $tpl->fetch("special/register"));
			}
		}
	}
	
	/**
	 * Confirm e-mail address
	 */
	function confirm() {
		$tpl =& Gene::getTemplate();
		$db =& Gene::getDatabase();
		
		/* Add additional stylesheets */
		$tpl->append("stylesheets", "register");
		$tpl->append("scripts", "register");
		
		if ($_SERVER['REQUEST_METHOD'] == "POST") {
			if (Gene::getSetting("require_email_confirm")) {
				$email = Gene_Request::getEmail("regemail", GENE_REQUEST_POST);
				if ($email) {
					/* Has anyone already registered with this e-mail address? */
					$q = $db->prepare ("SELECT * FROM ".Gene::tableName("users")." WHERE email=?");
					$res = $q->execute(array($email));
					if ($res->numRows()) {
						$tpl->assign ("errormsg", "It seems like someone has already registered with the e-mail <strong>".$email."</strong>. Please use the forgotten password feature link if you've forgotten your password.");
						$tpl->assign("finalbody", $tpl->fetch("special/confirmemail"));
						return;
					} else {
						// Generate confirmation key
						// We use crc32 because it is a bit easier to type than md5
						srand((double)microtime()*1000000);
						$key = sprintf("%u", crc32(time().$email.Gene::getSetting("gene_name").rand(0,30000)));
						$db->extended->autoExecute(
							Gene::tableName("email_confirm"),
							array(
								"email" => $email,
								"confirm_key" => $key,
								"timestamp" => time(),
							),
							MDB2_AUTOQUERY_INSERT
						);
						
						$baseurl = Gene::makeLink(Gene::specialID("Register"));
						$urlbits = parse_url($baseurl);
						if (isset($urlbits['query'])) {
							$url = $baseurl."&confirmemail=".$email."&confirmcode=".$key;
						} else {
							$url = $baseurl."?confirmemail=".$email."&confirmcode=".$key;
						}
						
						$message = "This email is being sent to you by ".Gene::getSetting("gene_name")." to confirm your account creation.\r\nIf you feel you received this email in error, please disregard it.\r\n\r\nTo confirm your account creation, please copy and paste the following address in to your web browser:\r\n".$url."\r\n\r\nAlternatively, return to ".Gene::getSetting("gene_name")." and enter the following details on the registration page:\r\n\r\nE-Mail Address: ".$email."\r\nConfirmation Code: ".$key."\r\n\r\nPlease confirm account creation within 7 days - otherwise your validation code will be disabled.";
						
						if (Gene::sendEmail($email, Gene::getSetting("gene_name")." Account Creation", $message)) {
							$tpl->assign ("success", true);
							$tpl->assign ("email", $email);
							$tpl->assign ("finalbody", $tpl->fetch("special/confirmemail2"));
						} else {
							$tpl->assign ("errormsg", "Unknown error.");
							$tpl->assign ("finalbody", $tpl->fetch("special/confirmemail"));
						}
					}
					
					$res->free();
				} else {
					$tpl->assign ("errormsg", "The e-mail address you entered was invalid.");
					$tpl->assign ("finalbody", $tpl->fetch("special/confirmemail"));
				}
			}
		} else {
			$tpl->assign ("finalbody", $tpl->fetch("special/confirmemail2"));
		}
	}
	
	/**
	 * Generate and show a CAPTCHA
	 */
	function captcha() {
		if (Gene::getSetting("reg_captcha")) {
			require_once ("Text/CAPTCHA.php");
			
			$options = array(
				"font_size" => 24,
				"font_path" => GENE_RESOURCES_DIR."fonts/",
				"font_file" => "vera.ttf",
			);
			
			$c = Text_CAPTCHA::factory('Image');
			$retval = $c->init(200, 80, null, $options);
			if (PEAR::isError($retval)) {
			    die ('Error generating CAPTCHA!');
			}
			
			$_SESSION['captcha_regphrase'] = $c->getPhrase();
			
			// Get CAPTCHA image (as PNG)
			$png = $c->getCAPTCHAAsPNG();
			if (PEAR::isError($png)) {
			    die('Error generating CAPTCHA!');
			}
			
			header ("Content-Type: image/png");
			echo $png;
		}
			
		exit();
	}
}

?>